package com.huarui.user.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import net.rubyeye.xmemcached.XMemcachedClient;

import org.apache.log4j.Logger;
import org.ewaf.framework.action.BaseAction;
import org.ewaf.framework.cookie.CookieManager;
import org.ewaf.framework.util.HttpUtil;
import com.huarui.user.model.CookieConstants;


public class RandomAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(RandomAction.class);
	private ByteArrayInputStream inputStream;
    private XMemcachedClient  memcachedClient; 
    

	public void setMemcachedClient(XMemcachedClient memcachedClient) {
		this.memcachedClient = memcachedClient;
	}

	public void setInputStream(ByteArrayInputStream inputStream) {
		this.inputStream = inputStream;
	}

	public ByteArrayInputStream getInputStream() {
		return inputStream;
	}
	
	public String verifyCode() throws Exception {
		// 在内存中创建图象

		char[] codeSequence =     { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
		'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
		'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', 
		'6','7','8','9'};  

		double []codePoint = {-0.01,-0.02,-0.03,-0.04,0.00,0.01,0.02,0.03,0.04};
		
		int width = 88, height = 40;
		try {
			BufferedImage image = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			// 获取图形上下文
			Graphics2D g = (Graphics2D)image.getGraphics();
			// 生成随机类
			Random random = new Random();
			// 设定背景色
			g.setColor(Color.WHITE);
			g.fillRect(6,2, width, height);
			// 设定字体
			//旋转字体
			g.rotate(codePoint[random.nextInt(9)], 20, 20);
			Font f=new Font("Times New Roman", Font.PLAIN,height-2);
			g.setFont(f);
			// 随机产生160条干扰线，使图象中的认证码不易被其它程序探测到
			g.setColor(getRandColor(180, 200));
			for (int i = 0; i < 160; i++) {
				int x = random.nextInt(width);
				int y = random.nextInt(height);
				int xl = random.nextInt(12);
				int yl = random.nextInt(12);
				g.drawLine(x, y, x + xl, y + yl);
			}

			// 取随机产生的认证码(6位数字)
			String sRand = "";
			for (int i = 0; i < 4; i++) {
				String rand= String.valueOf(codeSequence[random.nextInt(36)]);  
				sRand += rand;
				// 将认证码显示到图象中
				g.setColor(new Color(20+random.nextInt(110), 20+random
						.nextInt(110), 20+random.nextInt(110)));
				
				// 调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成,参数为相对图片的横纵坐标
				g.drawString(rand, 18 * i+4,36);
			
			}
			
			// 将token随机码存入COOKIE
			CookieManager cookie = new CookieManager(HttpUtil.getRequest());
			
			String code ="checkCode"+UUID.randomUUID().toString();
			cookie.setValue(CookieConstants.COOKIE_CODE, "code",code);
			cookie.saveCookie(HttpUtil.getResponse(), null, CookieConstants.Cookie_PATH,
					CookieConstants.COOKIE_CODE, CookieConstants.PERM_COOKIE_AGE);

			// 将认证码存入memcache		
			
			memcachedClient.set(code,240000,sRand);		
			
			// 图象生效
			g.dispose();
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
			ImageIO.write(image, "JPEG", imageOut);
			imageOut.close();
			ByteArrayInputStream input = new ByteArrayInputStream(output
					.toByteArray());
			this.setInputStream(input);
		} catch (TimeoutException e) {
			logger.debug(e.getMessage());
			e.printStackTrace();
		}

		return SUCCESS;
	}

	/*
	 * 给定范围获得随机颜色
	 */
	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}
	
}
